package com.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api/download")
public class DownloadController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("/excel/customer")
    public void exportAllCustomerExcel(HttpServletResponse response) {
        // 在方法开始时就设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=客户信息.xlsx");

        try {
            // 1、查询数据
            List<Customer> list = customerService.list();
            System.out.println("查询到 " + list.size() + " 条客户数据");

            if (list.isEmpty()) {
                // 如果没有数据，创建一个空列表避免NPE
                list = new ArrayList<>();
            }

            // 2、导出Excel
            EasyExcel.write(response.getOutputStream(), Customer.class)
                    .sheet("客户列表")
                    .doWrite(list);

            System.out.println("Excel导出成功");

        } catch (Exception e) {
            System.err.println("Excel导出异常: " + e.getClass().getSimpleName() + ": " + e.getMessage());
            e.printStackTrace();

            try {
                // 清除已写入的内容
                response.reset();
                // 设置错误响应
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ex) {
                System.err.println("错误响应发送失败: " + ex.getMessage());
            }
        }
    }
}